<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span
          style="
            display: inline-block;
            width: calc(100% - 51px);
            padding-right: 10px;
            text-align: right;
          "
        >
          <a-button
            @click="toggleScreen"
            icon="appstore"
            style="height: 20px; width: 20px; border: 0px"
          >
          </a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!--类型联动型号-->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="类型">
          <a-select
            placeholder="请选择"
            v-decorator.trim="['typeId', validatorRules.notBlank]"
            @change="typeChange"
          >
            <a-select-option
              :value="item.typeId"
              v-for="item in typeList"
              :key="item.typeId"
            >
              {{ item.typeDesc }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="型号">
          <a-select
            placeholder="请选择"
            v-decorator.trim="['modelId', validatorRules.notBlank]"
            @change="modelChange"
          >
            <a-select-option
              v-for="(item, index) in modelList"
              :key="index"
              :value="item.modelId"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <!--不能输入特殊字符 -->
          <a-input
            placeholder="名称"
            :maxLength="20"
            v-decorator.trim="[
              'name',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(
                    /[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,
                    ''
                  );
                },
              },
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="IP地址"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="IP地址"
            :maxLength="13"
            v-decorator.trim="[
              'ip',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^0-9.]/g, '');
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="端口" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="端口"
            :maxLength="10"
            v-decorator.trim="[
              'port',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^0-9]/g, '');
                },
              },
            ]"
          />
        </a-form-item>

        <a-form-item
          label="控制协议"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <!-- 在对应的协议组中选择 -->
          <a-select
            placeholder="请选择"
            v-decorator.trim="['ctrlProtocol', validatorRules.notBlank]"
          >
            <a-select-option
              v-for="item in ctrlProtocolList"
              :key="item"
              :value="item"
            >
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="访问用户名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="访问用户名"
            :maxLength="30"
            v-decorator.trim="[
              'userName',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^\w\/]/gi, '');
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item
          label="访问密码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="访问密码"
            :maxLength="30"
            v-decorator.trim="[
              'userPassword',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^\w\/]/gi, '');
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="启用" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-decorator.trim="['used', validatorRules.notBlank]">
            <a-radio value="1">是</a-radio>
            <a-radio value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="时间同步"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-select
            placeholder="请选择"
            v-decorator.trim="['timeSync', validatorRules.notBlank]"
          >
            <a-select-option value="1">是</a-select-option>
            <a-select-option value="0">否</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="NTP服务地址"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            :disabled="!(form.getFieldValue('timeSync') === '1')"
            placeholder="NTP服务地址"
            :maxLength="30"
            v-decorator.trim="[
              'ntpAddr',
              {
                rules:
                  form.getFieldValue('timeSync') === '1'
                    ? validatorRules.notBlank.rules
                    : rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^0-9.]/g, '');
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item
          label="NTP服务端口"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            :disabled="!(form.getFieldValue('timeSync') === '1')"
            placeholder="NTP服务端口"
            :maxLength="10"
            v-decorator.trim="[
              'ntpPort',
              {
                rules:
                  form.getFieldValue('timeSync') === '1'
                    ? validatorRules.notBlank.rules
                    : rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^0-9]/g, '');
                },
              },
            ]"
          />
        </a-form-item>

        <a-form-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="描述"
            v-decorator.trim="['devDesc']"
            :maxLength="40"
          />
        </a-form-item>
        <a-form-item label="地点" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="地点"
            v-decorator.trim="['location']"
            :maxLength="40"
          />
        </a-form-item>
      </a-form>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
      >
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>

      <a-button @click="handleNext" type="primary" :loading="confirmLoading"
        >下一步</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import pick from "lodash.pick";
import { getAction, postAction } from "@/api/manage";
import { join } from "path";
export default {
  name: "DevAddModal",
  components: {},
  data() {
    return {
      typeList: [],
      modelList: [],
      selectModel: [],
      ctrlProtocolList: [],
      model: {},
      form: this.$form.createForm(this),
      validatorRules: {
        notBlank: {
          rules: [
            {
              required: true,
              message: "请输入必填项!",
            },
          ],
        },
        isNumber: {
          rules: [
            {
              required: true,
              pattern: /^[1-9]\d*$/,
              message: "请输入数字类型!",
            },
          ],
        },
      },
      title: "新增",
      visible: false,
      modaltoggleFlag: true,
      confirmDirty: false,
      disableSubmit: false,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      modalWidth: 800,
      drawerWidth: 700,
      confirmLoading: false,
    };
  },
  created() {
    //初始化默认值
    this.form.getFieldDecorator("used", {
      initialValue: "1",
    });
    this.form.getFieldDecorator("timeSync", {
      initialValue: "1",
    });
    // this.form.getFieldDecorator("ntpPort", {
    //   initialValue: "123",
    // });
  },
  computed: {},

  methods: {
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth;
      } else {
        this.modalWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
    show() {
      //显示弹层
      this.visible = true;
      // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
      this.resetScreenSize();
      this.form.resetFields();
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            "typeId",
            "modelId",
            "name",
            "devDesc",
            "location",
            "used",
            "timeSync",
            "ntpAddr",
            "ntpPort",
            "ip",
            "port",
            "ctrlProtocol",
            "userName",
            "userPassword"
          )
        );
      });
    },
    typeChange(value) {
      //类型联动型号
      //清空类型
      this.modelList = [];

      //   this.form.setFieldsValue({ modelId: this.modelList[0].name });
      //联动查询
      getAction("/dev/model/getbytype?typeId=" + value).then((res) => {
        if (res.code == "00000") {
          this.modelList = res.data;
          console.log(this.modelList);

          console.log(res.data[0].modelId);
          this.modelChange(res.data[0].modelId);

          this.form.setFieldsValue({ modelId: res.data[0].modelId });
        } else {
          this.$message.warning("获取型号错误");
        }
      });
    },
    modelChange(value) {
      //   改变型号，默认协议改变

      this.modelList.some((item, i) => {
        if (value === item.modelId) {
          this.selectModel = item;
          return true;
        }
      });

      console.log(">>>>>>设备型号：" + JSON.stringify(this.selectModel));

      if (this.selectModel === undefined) {
        this.$message.warning("获取型号错误222");
        return;
      }

      try {
        this.ctrlProtocolList = this.selectModel.ctrlProtocolGroup.split(";");
        this.form.getFieldDecorator("ctrlProtocol", {
          initialValue: this.selectModel.defaultCtrlProtocol,
        });
      } catch (e) {
        //TODO handle the exception
        console.log("获取控制协议组失败！");
      }
    },
    close() {
      this.$emit("close");
      this.visible = false;
      this.disableSubmit = false;
    },
    handleNext() {
      //添加设备下一步
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let formData = Object.assign(this.model, values);
          postAction("/dev/add", formData)
            .then((res) => {
              if (res.code == "00000") {
                //子类绑定父类引组件的方法
                that.$emit("ok");
                that.$message.success("设备添加成功，即将跳转到摄像机管理页");
                //跳转新tab
                that.$router.push({
                  name: "/dev/camera",
                  params: {
                    devId: res.data,
                    domainType: 1,
                  },
                });
              } else {
                that.$message.warning("操作失败" + res.msg);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.close();
            });
        }
      });
    },
    handleCancel() {
      this.close();
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 700;
      }
    },
  },
  // 监听
  watch: {},
};
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>
